import os
import sys
from building import *
import xcc

xcc.SetDefaultRTOS('rtthread')

cwd = GetCurrentDir()

class RTCONFIG():
    def __init__(self,env):
        if(env['BOARD']=='versatilepb'):
            self.ARCH='arm'
            self.CPU='arm926'
        elif(env['BOARD']=='x86'):
            self.ARCH='ia32'
            self.CPU=''
        else:
            assert(0)
        self.CROSS_TOOL='gcc'
        self.PLATFORM='gcc'
        # SCons PreProcessor patch
        def start_handling_includes(self, t=None):
            """
            Causes the PreProcessor object to start processing #import,
            #include and #include_next lines.
        
            This method will be called when a #if, #ifdef, #ifndef or #elif
            evaluates True, or when we reach the #else in a #if, #ifdef,
            #ifndef or #elif block where a condition already evaluated
            False.
        
            """
            d = self.dispatch_table
            p = self.stack[-1] if self.stack else self.default_table
        
            for k in ('import', 'include', 'include_next', 'define'):
                d[k] = p[k]
        
        def stop_handling_includes(self, t=None):
            """
            Causes the PreProcessor object to stop processing #import,
            #include and #include_next lines.
        
            This method will be called when a #if, #ifdef, #ifndef or #elif
            evaluates False, or when we reach the #else in a #if, #ifdef,
            #ifndef or #elif block where a condition already evaluated True.
            """
            d = self.dispatch_table
            d['import'] = self.do_nothing
            d['include'] =  self.do_nothing
            d['include_next'] =  self.do_nothing
            d['define'] =  self.do_nothing
        PatchedPreProcessor = SCons.cpp.PreProcessor
        PatchedPreProcessor.start_handling_includes = start_handling_includes
        PatchedPreProcessor.stop_handling_includes = stop_handling_includes
        # parse rtconfig.h to get used component
        fc = '%s/menuconfig/%s/rtconfig.h'%(cwd,env['BOARD'])
        PreProcessor = PatchedPreProcessor()
        if(not os.path.exists(fc)):
            mk_rtconfig('%s/menuconfig/%s/.config'%(cwd,env['BOARD']))
        f = open(fc, 'r')
        contents = f.read()
        f.close()
        PreProcessor.process_contents(contents)
        BuildOptions = PreProcessor.cpp_namespace
        PrepareRTTHREAD(BuildOptions)


Import('asenv')

rtroot = '%s/rt-thread'%(cwd)

remove_components=['external','gdb','vmm','vbus','utilities']
RTT_ROOT=rtroot
rtconfig=RTCONFIG(asenv)
Export('remove_components')
Export('RTT_ROOT')
Export('rtconfig')

rtt = Package('https://github.com/RT-Thread/rt-thread.git')

MKSymlink(rtt,rtroot)

asenv.Append(CPPPATH=['%s/menuconfig/%s'%(cwd,asenv['BOARD'])])
asenv.Append(CPPPATH=['%s/../tinyos'%(cwd)])
asenv.Append(CPPPATH=['%s/components/drivers/include'%(rtroot)])
asenv.Append(CPPDEFINES=['USE_OSAL'])
asenv.Append(CPPDEFINES=['USE_STDRT'])
objs = Glob('*.c')

sys.path.append('%s/menuconfig'%(cwd))

list = os.listdir(rtroot)

for d in list:
    path = os.path.join(rtroot, d)
    if os.path.isfile(os.path.join(path, 'SConscript')):
        objs = objs + SConscript(os.path.join('rt-thread', d, 'SConscript'))

if('FTP' in asenv['MODULES']):
    objs += Glob('rt-thread/components/net/lwip-1.3.2/apps/ftpd.c')

if(asenv['BOARD'] == 'x86'):
    objs += Glob('rt-thread/bsp/x86/drivers/*.c')
    asenv.Append(CPPPATH=['%s/rt-thread/bsp/x86/drivers/include'%(cwd)])
    SrcRemove(objs, ['start_gcc.S','board.c'])

Return('objs')
